/******************************************************************************/
#include <stdio.h>
#include <string.h>
#include "jsontree.h"

static struct jsontree_object *tree;
static const int size = 128;
static char buf[128];
static int pos = 0;

static int
time_get(struct jsontree_context *js_ctx)
{
  char buf[20];

  snprintf(buf, 20, "8:08");
  jsontree_write_atom(js_ctx, buf);
  return 0;
}

static int
time_set(struct jsontree_context *js_ctx, struct jsonparse_state *parser)
{
  int type;
  char time[16];

  while((type = jsonparse_next(parser)) != 0) {
    if(type == JSON_TYPE_PAIR_NAME) {
      if(jsonparse_strcmp_value(parser, "time") == 0) {
        jsonparse_next(parser);
        jsonparse_next(parser);
		jsonparse_copy_value(parser, time, 16);
		printf("time is %s\n", time);
      }
    }
  }
  return 0;
}

static int 
output_temp(struct jsontree_context *path)
{
	char buf[5];
	snprintf(buf, sizeof(buf), "20");
	jsontree_write_atom(path, buf);
	return 0;
}


struct jsontree_callback json_time_callback =
	JSONTREE_CALLBACK(time_get, time_set);

static struct jsontree_callback temp_sensor_callback =
	JSONTREE_CALLBACK(output_temp, NULL);

static struct jsontree_string desc = JSONTREE_STRING("Mote");
static struct jsontree_string temp_unit = JSONTREE_STRING("Celcius");

JSONTREE_OBJECT(node_tree,
						JSONTREE_PAIR("node-type", &desc),
						JSONTREE_PAIR("time", &json_time_callback));

JSONTREE_OBJECT(temp_sensor_tree,
						JSONTREE_PAIR("unit", &temp_unit),
						JSONTREE_PAIR("value", &temp_sensor_callback));

/* complete node tree */
JSONTREE_OBJECT(objtree,
						JSONTREE_PAIR("node", &node_tree),
						JSONTREE_PAIR("temp", &temp_sensor_tree));

static int
putchar_test(int c)
{
  if(pos <= size) {
    buf[pos++] = c;
    return c;
  } 
  return 0;
} 


int main(int argc, char **argv)
{
	tree = &objtree;
	char *callback_json_path;

	printf("hello,world\n");
	struct jsontree_context json;

	json.values[0] = (struct jsontree_value *)tree;
	jsontree_reset(&json);
	printf("path: %d, depth: %d\n",json.path, json.depth);
	json.path = json.depth;
	printf("path: %d, depth: %d\n",json.path, json.depth);

	json.putchar = putchar_test;
	while(jsontree_print_next(&json) && json.path <= json.depth);

	printf("size: %d\n", pos);
	buf[pos] = '\0';

	printf("out is %s\n", buf);

	return 0;
}
